package com.kuang.gulimall.product.web;


import com.kuang.gulimall.product.entity.CategoryEntity;
import com.kuang.gulimall.product.service.CategoryService;
import com.kuang.gulimall.product.vo.webVo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {


    @Autowired
    CategoryService categoryService;

    //注入分布式锁
    @Autowired
    RedissonClient redisson;

    //测试读写锁
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping({"/","/index"})
    public String indexPage(Model model){

        List<CategoryEntity> categoryEntityList = categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntityList);
        //视图解析器解析
        return "index";
    }

    @ResponseBody
    //index/catalog.json
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCataJson(){

        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1,获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");

        //2,加锁
//        lock.lock();//阻塞式等待。相对于原来的自旋，这是阻塞式的
        lock.lock(10, TimeUnit.SECONDS);//10s后自动解锁，会不会自动续期？自己设置过期时间之后，不能自动续期。
        //1，如果传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定的时间。
        //2，如果我们未指定锁的超时时间，就使用30*1000【lockWatchdogTimeout看门狗的默认时间】
        //如果自己指定了时间，一定要指定的时间超过业务时间，因为不能续期，需要注意
        // 只要占锁成功，就会启动一个定时任务。
        //省掉了整个续期操作。手动解锁
        //
        try{
            System.out.println("加锁成功，执行业务");
            Thread.sleep(300);
        } catch (Exception e) {

        } finally {
            //3，解锁
            System.out.println("释放锁"+Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }

    //读写锁
    @ResponseBody
    @GetMapping("/write")
    public String writeValue(){

        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        //加锁
        RLock rLock = readWriteLock.writeLock();
        try {
            //1，改数据加写锁，读数据加读锁
            rLock.lock();
            s = UUID.randomUUID().toString();
            Thread.sleep(3000);
            redisTemplate.opsForValue().setIfAbsent("writeValue",s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //解锁
            rLock.unlock();
        }
        return s;
    }
    //读写锁
    @ResponseBody
    @GetMapping("/read")
    public String readValue(){
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = readWriteLock.writeLock();
        readWriteLock.readLock();
        try {
            //开启读锁
            s = (String) redisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    //锁门问题（闭锁）
    //
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException{
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await(); //等待闭锁都完成

        return "放假了。。";
    }

    @ResponseBody
    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown(); //记数减一

        return id+"班的人都走了。。。";
    }

    //停车问题(分布式信号量,用来做分布式限流,限制每一个应用的流量)
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException{
        RSemaphore park = redisson.getSemaphore("park");
//        park.acquire();//获取一个信号量，获取一个值,占一个车位，阻塞式等待，等待释放才能停
        boolean b = park.tryAcquire();
        if (b) {
            //执行业务
            return "占车位ok";
        }else {
            return "error";
        }

    }

    //停车问题(分布式信号量)
    @GetMapping("/go")
    @ResponseBody
    public String goCar() throws InterruptedException{
        RSemaphore park = redisson.getSemaphore("park");
        park.release();//释放一个车位

        return "释放车位ok";
    }
}
